package com.example.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springboot.common.Constants;
import com.example.springboot.common.Page;
import com.example.springboot.common.Result;
import com.example.springboot.entity.CComment;
import com.example.springboot.entity.SComment;
import com.example.springboot.entity.Solution;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.SCommentMapper;
import com.example.springboot.service.ISCommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.service.ISolutionService;
import com.example.springboot.utils.SensitiveWordUtil;
import com.example.springboot.utils.TimeUtil;
import com.example.springboot.utils.TokenUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class SCommentServiceImpl extends ServiceImpl<SCommentMapper, SComment> implements ISCommentService {

    @Resource
    private SCommentMapper sCommentMapper;
    @Resource
    private ISCommentService commentService;
    @Resource
    private ISolutionService solutionService;

    @Override   //获取方案的评论
    public List<SComment> getCommentsBySolution(Integer solutionId) {
        //查找该创意下所有已发布评论
        List<SComment> commentList = sCommentMapper.getCommentsBySolution(solutionId);
        for (SComment sComment : commentList){
            sComment.setMine(sComment.getUserId().equals(Objects.requireNonNull(TokenUtils.getCurrentUser()).getId()));
            sComment.setRelativeTime(TimeUtil.createRelative(sComment.getCreateTime()));
        }
        //查找所有父级评论
        List<SComment> originList = commentList.stream().filter(sComment -> sComment.getOriginId() == null).collect(Collectors.toList());
        //对每个父级评论设置子评论列表
        for (SComment origin : originList) {
            //回复评论列表
            List<SComment> childrenList = commentList.stream().filter(sComment -> origin.getId().equals(sComment.getOriginId())).collect(Collectors.toList());
            //对其中的评论设置父级评论的用户id和昵称
            childrenList.forEach(sComment -> {
                commentList.stream().filter(c1 -> c1.getId().equals(sComment.getPid())).findFirst().ifPresent((v -> {
                    sComment.setPUserId(v.getUserId());
                    sComment.setPNickname(v.getNickname());
                }));
            });
            origin.setChildren(childrenList);
        }
        return originList;
    }

    @Override   //获取方案的评论数
    public int getCount(Integer solutionId) {
        QueryWrapper<SComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("solution_id",solutionId);
        return sCommentMapper.selectList(queryWrapper).size();
    }

    @Override   //插入评论、首先判断pid、originId是否存在
    public SComment insert(SComment sComment) throws IOException {
        Solution solution;
        try {
            solution = solutionService.getById(sComment.getSolutionId());
        }catch (Exception e) {
            throw new ServiceException(Constants.CODE_500,"系统错误");
        }
        if (solution == null)
            throw new ServiceException(Constants.CODE_600,"方案不存在");
        else if (!solution.getStatement().equals("已发布"))
            throw new ServiceException(Constants.CODE_600,"方案不存在");
        sComment.setContent(SensitiveWordUtil.sensitiveHelper(sComment.getContent()));
        QueryWrapper<SComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",sComment.getOriginId()).or().eq("id",sComment.getPid());
        List<SComment> back = sCommentMapper.selectList(queryWrapper);
        if (sComment.getPid() == null && sComment.getOriginId() == null)
            sCommentMapper.insert(sComment);
        else if (sComment.getOriginId().equals(sComment.getPid())) {
            if (back.size() == 0)
                return null;
            sCommentMapper.insert(sComment);
        }
        else {
            if (back.size() != 2)
                return null;
            sCommentMapper.insert(sComment);
        }
        return sComment;
    }

    @Override   //删除评论
    public boolean deleteOne(Integer id) {
        QueryWrapper<SComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid",id).or().eq("origin_id",id).or().eq("id",id);
        return commentService.remove(queryWrapper);
    }

    @Override   //删除方案下的所有评论
    public boolean deleteBySolution(Integer solutionId) {
        QueryWrapper<SComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("solution_id",solutionId);
        return commentService.remove(queryWrapper);
    }

    @Override   //管理员获取评论列表
    public Result adminGet(int PageNum, int PageSize, String content) {
        QueryWrapper<SComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("content","该评论包含敏感词汇，已被屏蔽。");
        queryWrapper.like("content",content);
        List<SComment> sCommentList = commentService.list(queryWrapper);
        sCommentList.sort(Comparator.comparing(SComment::getCreateTime).reversed());
        Page page = new Page();
        return Result.success(page.startPage(sCommentList,PageNum,PageSize));
    }

    @Override   //管理员处理违规评论
    public Result processComment(Integer id) {
        SComment find;
        try {
            find = commentService.getById(id);
        }catch (Exception e) {
            throw new ServiceException(Constants.CODE_500,"系统错误");
        }
        if (find == null)
            return Result.error(Constants.CODE_600,"该评论不存在");
        SComment sComment = new SComment();
        sComment.setId(id);
        sComment.setContent("该评论包含敏感词汇，已被屏蔽。");
        if (commentService.saveOrUpdate(sComment))
            return Result.success("处理成功");
        return Result.error(Constants.CODE_600,"处理失败");
    }
}

